package com.neuedu.shop.controller;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

/**
 * 负责生成验证码的Controller
 */
@Controller
public class CodeController {
    @RequestMapping("/code")
    public void generatorCode(HttpServletResponse response, HttpSession session) throws IOException {
        System.out.println("进来了！");
        //生成验证码图片
        //1、设置向前台输出的文件类型
        response.setContentType("image/jpeg");
        /* 2 画图 */
        //BufferedImage:内存映象对象
        BufferedImage image = new BufferedImage(60, 20,BufferedImage.TYPE_INT_RGB);
        Random r = new Random();
        //获得画笔
        Graphics g = image.getGraphics();
        //设置背景颜色
        g.setColor(new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256)));
        //填充背景颜色
        g.fillRect(0, 0, 60, 20);
        //设置前景颜色
        g.setColor(new Color(0,0,0));
        //生成随机数
        String number = String.valueOf(r.nextInt(100_000));

        //将number随机数绑定到session对象中
        session.setAttribute("number",number);

        //画到图片上
        g.drawString(number, 5, 15);
        /* 3 压缩图片并输出 */
        //获得字节输出流，因为要输出的是图像压缩之后
        //的字节数组，所以，不能用PrintWriter。
        OutputStream os = response.getOutputStream();
        //将图片压缩，输出
        JPEGImageEncoder encoder =  JPEGCodec.createJPEGEncoder(os);
        encoder.encode(image);

    }

}
